import { InfoCircleOutlined } from '@ant-design/icons'
import { useModel, useParams } from '@umijs/max'
import { Button, Form, Modal, Select, App, Input, Tooltip, Radio } from 'antd'
import { useState } from 'react'
import './CreditBtnGroup.less'
import { useEffect } from 'react'

const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 18 } }

const overdueLevel = [
  { value: 1, label: '正常(0-30天)' },
  { value: 2, label: '关注(31-60天)' },
  { value: 3, label: '次级(61-120天)' },
  { value: 4, label: '可疑(121-180天)' },
  { value: 5, label: '损失(180以上)' }
]

function CreditBtnGroup({ leaseTerm, user_id, order_sn }) {
  const {
    UserCreateSign,
    ApplyCreditQuery,
    GetCreditQueryResult,
    ApplyContractLeasing,
    ApplyResultQuery,
    Repayment,
    SettleDataReport,
    SettleReportConfirm,
    GetSettleResult,
    SettleRecovery
  } = useModel('RiskControl')

  const [modalConfirmLoading, setModalConfirmLoading] = useState(false) // 弹窗确认按钮loading
  const [creditReportingModal, setCreditReportingModal] = useState(false) // 弹窗

  const [btnLoading, setBtnLoading] = useState(false) // 按钮loading

  const { message, modal } = App.useApp()

  const [currentReportingEvent, setCurrentReportingEvent] = useState('') // 当前征信上报事件

  const [orderBillNum, setOrderBillNum] = useState([]) // 账单期数

  const [repaymentFormRef] = Form.useForm() // 每期还款表单

  const [settleAndOverdueReportingFormRef] = Form.useForm() // 结清/逾期上报表单

  const [settleFormRef] = Form.useForm() // 结清表单

  // 打开弹窗按钮
  const handleReporting = async item => {
    setBtnLoading(true)

    // 获取账单期数
    if (item.key === 'repayment') {
      if (leaseTerm) {
        let list = []
        // eslint-disable-next-line array-callback-return
        Array.from({ length: leaseTerm }).map((_, index) => {
          list.push({
            value: index + 1,
            label: `第 ${index + 1} 期`
          })
        })

        setOrderBillNum(list)
      }
      repaymentFormRef.resetFields()
    }

    setBtnLoading(false)
    setCurrentReportingEvent(item)
    setCreditReportingModal(true)
  }

  // 处理弹窗确认事件
  const creditReportingModalConfirm = async () => {
    const { key } = currentReportingEvent
    setModalConfirmLoading(true)
    let res = await creditBtnList.find(item => item.key === key).methods()
    if (!res) {
      setModalConfirmLoading(false)
    }
  }

  // 渲染提示内容
  const renderTipsText = (key, text) => {
    return (
      currentReportingEvent?.key === key && (
        <div className='tips_text'>
          <InfoCircleOutlined style={{ color: '#FF7D00' }} /> {text}
        </div>
      )
    )
  }

  const creditBtnList = [
    {
      key: 'user_create_sign',
      name: '生成文件',
      bgColor: '#EEFEFB',
      color: '#77CAC6',
      tips: '操作生成文件成功2分钟后再操作查看',
      methods: async () => {
        let param = {
          user_id,
          order_sn
        }

        let res = await UserCreateSign(param)
        if (res) {
          message.success('文件生成成功')
          setCreditReportingModal(false)
        }
      }
    },
    {
      key: 'query_credit',
      name: '申请查询',
      bgColor: '#EEFEFB',
      color: '#77CAC6',
      tips: '操作申请查询成功2分钟后再操作查看',
      methods: async () => {
        let param = {
          user_id,
          order_sn
        }

        let applyRes = await ApplyCreditQuery(param)
        if (applyRes) {
          message.success('申请征信查询成功')
          setCreditReportingModal(false)
        }
      }
    },
    {
      key: 'credit_result',
      name: '征信结果',
      bgColor: '#F1E7FE',
      color: '#6938CE',
      tips: '查看当前的征信查询结果',
      methods: async () => {
        let res = await GetCreditQueryResult({ order_sn })
        if (res) {
          setCreditReportingModal(false)
          window.open(res)
        }
      }
    },
    {
      key: 'application_guarantee',
      name: '申请担保',
      bgColor: '#FCF6E7',
      color: '#E5A762',
      tips: '30天内的审核通过后订单才支持申请担保，请及时操作',
      methods: async () => {
        let res = await ApplyContractLeasing({ order_sn })
        if (res) {
          message.success('申请担保成功')
          setCreditReportingModal(false)
        }
      }
    },
    {
      key: 'guarantee_result',
      name: '担保结果',
      bgColor: '#ECF8FE',
      color: '#6294F7',
      tips: '操作申请担保成功2分钟后再操作查看',
      methods: async () => {
        let res = await ApplyResultQuery({ order_sn })
        if (res) {
          message.success('担保结果查询成功')
          setCreditReportingModal(false)
          const { guaranteeContract, leaseContract } = res.result
          modal.info({
            title: '担保结果',
            content: (
              <div>
                <p>
                  <a target='_blank' href={guaranteeContract} rel='noreferrer'>
                    担保合同(点击查看)
                  </a>
                </p>
                <p>
                  <a target='_blank' href={leaseContract} rel='noreferrer'>
                    租赁合同(点击查看)
                  </a>
                </p>
              </div>
            )
          })
        }
      }
    },
    {
      key: 'repayment',
      name: '每期还款',
      bgColor: '#F8EAE8',
      color: '#D86565',
      tips: '客户每期还款均需进行还款数据上报，若订单结清时有漏报需操作每期还款补报',
      methods: async () => {
        try {
          await repaymentFormRef.validateFields()
          let params = {
            order_sn,
            ...repaymentFormRef.getFieldsValue()
          }
          let res = await Repayment(params)
          if (res) {
            message.success('追加还款成功')
            setCreditReportingModal(false)
          }
        } catch (e) {
          setModalConfirmLoading(false)
        }
      }
    },
    {
      key: 'settle_and_overdue_reporting',
      name: '结清/逾期上报',
      bgColor: '#E8FFEA',
      color: '#00B42A',
      tips: '订单正常完结操作上报；逾期上报会在订单完结后统一上报（连续逾期三期可选择逾期上报提前完结，并发送短信通知客户告知逾期）',
      methods: async () => {
        try {
          await settleAndOverdueReportingFormRef.validateFields()
          let params = {
            order_sn,
            ...settleAndOverdueReportingFormRef.getFieldsValue()
          }
          let res = await SettleDataReport(params)
          if (res) {
            let confirmRes = await SettleReportConfirm({
              settleConfirm: 1,
              order_sn
            })
            if (confirmRes) {
              message.success('上报成功')
              setCreditReportingModal(false)
            }
          }
        } catch (e) {
          setModalConfirmLoading(false)
        }
      }
    },
    {
      key: 'settle_and_overdue_result',
      name: '结清/逾期结果',
      bgColor: '#F7E8F1',
      color: '#D964B0',
      tips: '请确认是否上报（二次确认弹窗文案）结清/逾期结果查看：统一固定时间推送',
      methods: async () => {
        let res = await GetSettleResult({ order_sn })
        if (res) {
          setCreditReportingModal(false)
          modal.info({
            title: '结清/逾期结果',
            content: <div>{res.msg}</div>
          })
        }
      }
    },
    {
      key: 'settle',
      name: '结清追偿',
      bgColor: '#FEFCE8',
      color: '#E9C04A',
      tips: '客户还完逾期金额后操作',
      methods: async () => {
        try {
          await settleFormRef.validateFields()
          let params = {
            order_sn,
            ...settleFormRef.getFieldsValue()
          }
          let res = await SettleRecovery(params)
          if (res) {
            message.success('结清追偿成功')
            setCreditReportingModal(false)
          }
        } catch (e) {
          setModalConfirmLoading(false)
        }
      }
    }
  ]

  return (
    <div>
      <div className='header_credit'>
        <div key='header_content'>
          {creditBtnList.map(item => {
            return (
              <Tooltip placement='topLeft' title={item.tips} key={item.key}>
                <Button
                  loading={btnLoading}
                  style={{
                    background: item.bgColor,
                    color: item.color,
                    border: `1px solid ${item.color}`,
                    marginLeft: '10px'
                  }}
                  onClick={() => handleReporting(item)}
                >
                  {item.name}
                </Button>
              </Tooltip>
            )
          })}
        </div>
      </div>

      <Modal
        title={currentReportingEvent?.name}
        mask
        open={creditReportingModal}
        width={500}
        confirmLoading={modalConfirmLoading}
        onCancel={() => setCreditReportingModal(false)}
        onOk={() => creditReportingModalConfirm()}
        okText={'确认'}
        maskClosable={false}
      >
        <div style={{ padding: '20px 0' }}>
          {renderTipsText('user_create_sign', '您确定需要生成该用户征信文件吗?')}

          {renderTipsText('query_credit', '您确定需要查询该用户征信吗?')}

          {renderTipsText('credit_result', '确认查询后将会进行征信数据展示')}

          {renderTipsText('application_guarantee', '确认申请担保吗?')}

          {renderTipsText('guarantee_result', '确认查询后将会进行担保数据展示')}

          {
            /* 每期还款 */
            currentReportingEvent?.key === 'repayment' && (
              <Form
                form={repaymentFormRef}
                name='repaymentForm'
                {...formItemLayout}
                initialValues={{ bill_num: 1, repayType: 1 }}
              >
                <Form.Item name='bill_num' label='账单期数 : ' rules={[{ required: true, message: '请选择期数' }]}>
                  <Select placeholder={'请选择期数'} options={orderBillNum} />
                </Form.Item>
                <Form.Item
                  extra='指用户还款了但是没在账单还款日还款，后来才还款的情况'
                  name='repayType'
                  label='还款类型 : '
                  rules={[{ required: true, message: '请选择还款类型' }]}
                >
                  <Radio.Group>
                    <Radio value={1}>正常还款</Radio>
                    <Radio value={2}>逾期还款</Radio>
                  </Radio.Group>
                </Form.Item>
              </Form>
            )
          }

          {
            /* 结清/逾期上报 */
            currentReportingEvent?.key === 'settle_and_overdue_reporting' && (
              <Form
                form={settleAndOverdueReportingFormRef}
                name='settleAndOverdueReportingForm'
                {...formItemLayout}
                initialValues={{ fivecate: 1, type: 0 }}
              >
                <Form.Item name='fivecate' label='逾期级别 : ' rules={[{ required: true, message: '请选择逾期级别' }]}>
                  <Select placeholder={'请选择逾期级别'} options={overdueLevel} />
                </Form.Item>
                <Form.Item
                  name='type'
                  label='结清上报类型 : '
                  rules={[{ required: true, message: '请选择结清上报类型' }]}
                >
                  <Radio.Group>
                    <Radio value={0}>逾期</Radio>
                    <Radio value={1}>正常完结</Radio>
                  </Radio.Group>
                </Form.Item>
              </Form>
            )
          }

          {renderTipsText('settle_and_overdue_result', '确认查询后将会进行结清/逾期结果数据展示')}

          {
            /* 结清 */
            currentReportingEvent?.key === 'settle' && (
              <Form form={settleFormRef} name='settleForm' {...formItemLayout} initialValues={{ fivecate: 1, type: 0 }}>
                <Form.Item name='fivecate' label='逾期级别 : ' rules={[{ required: true, message: '请选择逾期级别' }]}>
                  <Select placeholder={'请选择逾期级别'} options={overdueLevel} />
                </Form.Item>
              </Form>
            )
          }
        </div>
      </Modal>
    </div>
  )
}

export default CreditBtnGroup
